#!/usr/bin/env coffee

import {dirname,join} from 'path'
import {rename,writeFile,readFile,opendir} from 'fs/promises'
import thisdir from '@rmw/thisdir'

replace = (node,txt)=>
  node = "#{node}.node"
  pos = txt.indexOf node
  if pos < 0
    return

  begin = txt.lastIndexOf('(',pos)+1
  end = txt.indexOf(')',pos)
  [txt[...begin],"__dirname,\"#{node}\"",txt[end..]].join ''

parse = (node_li, fp)=>
  txt = await readFile fp,'utf8'

  change = false
  for node from node_li
    t = replace node,txt
    if t
      change = true
      txt = t
  if change
    console.log fp
    await writeFile fp,txt
  return


DIR = join(
  dirname thisdir import.meta
  'node_modules'
)

do =>

  li = {
    iohook:[
      'iohook'
    ]
  }
  for [name,node_li] from Object.entries li
    dir = join(DIR,name)
    for await {name} from await opendir dir
      if name.endsWith '.js'
        await parse node_li,join(dir, name)
  return


###
BFILE = baseX '!$-.0123456789_abcdefghijklmnopqrstuvwxyz'

encode = (n)=>
  bin = Buffer.allocUnsafe 6
  bin.writeUIntBE(n,0,6)
  for i,pos in bin
    if i!=0
      break
  BFILE.encode bin[pos..]

DIR = join(
  dirname dirname thisdir import.meta
  'ci/app'
)

css_js = new Map()
to_replace = []
all = new Set()

for await fp from await opendir DIR
  if not fp.isFile()
    continue
  fp = fp.name
  all.add fp
  name = fp.split('.')
  ext = name.at -1
  hex = name.at -2
  if ~['html','css','js'].indexOf(ext)
    css_js.set(
      fp
      await readFile(join(DIR,fp),'utf8')
    )
  if fp!='m.js'
    to_replace.push fp

ID = new Map()

fp_name = new Map()

for i from to_replace
  ext = i[i.lastIndexOf('.')+1..]
  if ext == 'html'
    ext = 'htm'
  id = ID.get(ext) or 0
  loop
    name = encode(id++)+'.'+ext
    if not all.has name
      break
  ID.set(ext,id)
  fp_name.set(i,name)
  await rename(
    join(DIR,i)
    join(DIR,name)
  )

for [k,v] from css_js.entries()
  for [f,t] from fp_name.entries()
    v = v.replaceAll(f,t)

  await writeFile(
    join DIR,(fp_name.get(k) or k)
    v
  )

process.exit()


#console.log css_js
###
